package com.ruoyi.system.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.system.domain.BizPurchaseOrderItem;
import com.ruoyi.system.mapper.BizPurchaseOrderMapper;
import com.ruoyi.system.domain.BizPurchaseOrder;
import com.ruoyi.system.service.IBizPurchaseOrderService;
import com.ruoyi.system.domain.BizPurchaseOrderItemView;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import java.math.BigDecimal;

/**
 * 采购订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-20
 */
@Service
public class BizPurchaseOrderServiceImpl implements IBizPurchaseOrderService 
{
    @Autowired
    private BizPurchaseOrderMapper bizPurchaseOrderMapper;

    /**
     * 查询采购订单
     * 
     * @param orderId 采购订单主键
     * @return 采购订单
     */
    @Override
    public BizPurchaseOrder selectBizPurchaseOrderByOrderId(Long orderId)
    {
        return bizPurchaseOrderMapper.selectBizPurchaseOrderByOrderId(orderId);
    }

    /**
     * 查询采购订单列表
     * 
     * @param bizPurchaseOrder 采购订单
     * @return 采购订单
     */
    @Override
    public List<BizPurchaseOrder> selectBizPurchaseOrderList(BizPurchaseOrder bizPurchaseOrder)
    {
        return bizPurchaseOrderMapper.selectBizPurchaseOrderList(bizPurchaseOrder);
    }

    /**
     * 新增采购订单
     * 
     * @param bizPurchaseOrder 采购订单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertBizPurchaseOrder(BizPurchaseOrder bizPurchaseOrder)
    {
        // 自动生成订单编号：PO + yyyyMMdd + 三位流水
        if (StringUtils.isEmpty(bizPurchaseOrder.getOrderNo())) {
            bizPurchaseOrder.setOrderNo(generateOrderNo());
        }
        // 设置审计字段（避免 created_by/created_time 为空导致插入失败）
        if (StringUtils.isEmpty(bizPurchaseOrder.getCreatedBy())) {
            bizPurchaseOrder.setCreatedBy(SecurityUtils.getUsername());
        }
        if (bizPurchaseOrder.getCreatedTime() == null) {
            bizPurchaseOrder.setCreatedTime(DateUtils.getNowDate());
        }
        int rows = bizPurchaseOrderMapper.insertBizPurchaseOrder(bizPurchaseOrder);
        insertBizPurchaseOrderItem(bizPurchaseOrder);
        return rows;
    }

    /**
     * 修改采购订单
     * 
     * @param bizPurchaseOrder 采购订单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateBizPurchaseOrder(BizPurchaseOrder bizPurchaseOrder)
    {
        // 依据订单编号删除并重建明细
        bizPurchaseOrderMapper.deleteBizPurchaseOrderItemByOrderNo(bizPurchaseOrder.getOrderNo());
        insertBizPurchaseOrderItem(bizPurchaseOrder);
        // 设置更新审计字段
        bizPurchaseOrder.setUpdatedBy(SecurityUtils.getUsername());
        bizPurchaseOrder.setUpdatedTime(DateUtils.getNowDate());
        return bizPurchaseOrderMapper.updateBizPurchaseOrder(bizPurchaseOrder);
    }

    /**
     * 批量删除采购订单
     * 
     * @param orderIds 需要删除的采购订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteBizPurchaseOrderByOrderIds(Long[] orderIds)
    {
        bizPurchaseOrderMapper.deleteBizPurchaseOrderItemByOrderNos(orderIds);
        return bizPurchaseOrderMapper.deleteBizPurchaseOrderByOrderIds(orderIds);
    }

    /**
     * 删除采购订单信息
     * 
     * @param orderId 采购订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteBizPurchaseOrderByOrderId(Long orderId)
    {
        // 先查订单编号，再删除其明细
        BizPurchaseOrder order = bizPurchaseOrderMapper.selectBizPurchaseOrderByOrderId(orderId);
        if (order != null && StringUtils.isNotEmpty(order.getOrderNo())) {
            bizPurchaseOrderMapper.deleteBizPurchaseOrderItemByOrderNo(order.getOrderNo());
        }
        return bizPurchaseOrderMapper.deleteBizPurchaseOrderByOrderId(orderId);
    }

    /**
     * 查询采购订单明细联表视图列表
     */
    @Override
    public List<BizPurchaseOrderItemView> selectBizPurchaseOrderItemJoinedList(BizPurchaseOrderItemView view) {
        return bizPurchaseOrderMapper.selectBizPurchaseOrderItemJoinedList(view);
    }

    /**
     * 新增采购订单明细信息
     * 
     * @param bizPurchaseOrder 采购订单对象
     */
    public void insertBizPurchaseOrderItem(BizPurchaseOrder bizPurchaseOrder)
    {
        List<BizPurchaseOrderItem> bizPurchaseOrderItemList = bizPurchaseOrder.getBizPurchaseOrderItemList();
        Long orderId = bizPurchaseOrder.getOrderId();
        if (StringUtils.isNotNull(bizPurchaseOrderItemList))
        {
            List<BizPurchaseOrderItem> list = new ArrayList<BizPurchaseOrderItem>();
            for (BizPurchaseOrderItem bizPurchaseOrderItem : bizPurchaseOrderItemList)
            {
                // 绑定主表的订单ID与订单编号
                bizPurchaseOrderItem.setOrderId(orderId);
                bizPurchaseOrderItem.setOrderNo(bizPurchaseOrder.getOrderNo());
                // 设置明细审计字段
                if (StringUtils.isEmpty(bizPurchaseOrderItem.getCreatedBy())) {
                    bizPurchaseOrderItem.setCreatedBy(SecurityUtils.getUsername());
                }
                if (bizPurchaseOrderItem.getCreatedTime() == null) {
                    bizPurchaseOrderItem.setCreatedTime(DateUtils.getNowDate());
                }
                // 数量默认值与未打码数量计算
                BigDecimal orderQty = bizPurchaseOrderItem.getOrderQuantity() != null ? bizPurchaseOrderItem.getOrderQuantity() : BigDecimal.ZERO;
                BigDecimal barcoded = bizPurchaseOrderItem.getBarcodedQuantity() != null ? bizPurchaseOrderItem.getBarcodedQuantity() : BigDecimal.ZERO;
                if (barcoded.signum() < 0) {
                    barcoded = BigDecimal.ZERO;
                }
                BigDecimal unbarcoded = orderQty.subtract(barcoded);
                if (unbarcoded.signum() < 0) {
                    unbarcoded = BigDecimal.ZERO;
                }
                bizPurchaseOrderItem.setBarcodedQuantity(barcoded);
                bizPurchaseOrderItem.setUnbarcodedQuantity(unbarcoded);
                if (bizPurchaseOrderItem.getPutawayQuantity() == null) {
                    bizPurchaseOrderItem.setPutawayQuantity(BigDecimal.ZERO);
                }
                // 默认状态与删除标志
                if (StringUtils.isEmpty(bizPurchaseOrderItem.getItemStatus())) {
                    bizPurchaseOrderItem.setItemStatus("PENDING");
                }
                if (StringUtils.isEmpty(bizPurchaseOrderItem.getDelFlag())) {
                    bizPurchaseOrderItem.setDelFlag("0");
                }
                list.add(bizPurchaseOrderItem);
            }
            if (list.size() > 0)
            {
                bizPurchaseOrderMapper.batchBizPurchaseOrderItem(list);
            }
        }
    }

    /**
     * 更新采购订单明细状态（例如 QUALITY_PASSED / QUALITY_FAILED）
     */
    @Override
    public int updateBizPurchaseOrderItemStatus(Long itemId, String itemStatus) {
        String updatedBy = SecurityUtils.getUsername();
        java.util.Date updatedTime = DateUtils.getNowDate();
        return bizPurchaseOrderMapper.updateBizPurchaseOrderItemStatus(itemId, itemStatus, updatedBy, updatedTime);
    }

    /**
     * 生成订单编号：PO + yyyyMMdd + 三位流水（001 开始）
     */
    private String generateOrderNo() {
        String dateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String prefix = "PO" + dateStr;
        String maxOrderNo = bizPurchaseOrderMapper.selectMaxOrderNoByDate(prefix);
        int next = 1;
        if (StringUtils.isNotEmpty(maxOrderNo)) {
            String suffix = maxOrderNo.substring(prefix.length());
            try {
                next = Integer.parseInt(suffix) + 1;
            } catch (Exception e) {
                next = 1;
            }
        }
        return prefix + String.format("%03d", next);
    }
}
